#!/usr/bin/env bash
# SPDX-License-Identifier: LGPL-3.0-or-later
# Copyright (C) 2014 Stony Brook University
# Copyright (C) 2019 Invisible Things Lab
# Copyright (C) 2021 Intel Corporation
#                    Michał Kowalczyk <mkow@invisiblethingslab.com>
#                    Wojtek Porczyk <woju@invisiblethingslab.com>

PAL_CMD=@PAL_CMD@
LIBPAL_PATH=@LIBPAL_PATH@
HOST_PAL_PATH=@HOST_PAL_PATH@
SGX=@SGX@

APPLICATION=
ENVS=()
PREFIX=()

if [ "$GDB" == "1" ]; then
    PREFIX=("gdb" "-q")
    if [ -n "$INSIDE_EMACS" ]; then
        PREFIX+=("-i=mi")
    fi
    if [ 0"$SGX" -gt 0 ]; then
        PREFIX+=("-x" "$HOST_PAL_PATH/gdb_integration/gramine_sgx_gdb.py")
        ENVS+=("LD_PRELOAD=$HOST_PAL_PATH/gdb_integration/sgx_gdb.so:$LD_PRELOAD")
    else
        PREFIX+=("-x" "$HOST_PAL_PATH/gdb_integration/gramine_linux_gdb.py")
    fi
    if [ "$GDB_SCRIPT" != "" ]; then
        # Run a script in batch mode, and without TTY (so that it can be piped, redirected etc.)
        PREFIX+=("-x" "$GDB_SCRIPT" "-batch" "-tty=/dev/null")
    fi
    PREFIX+=("--args")
fi

if [ "$PERF" == "1" ]; then
    PREFIX=(perf stat)
fi

while [ "$1" != "" ];
do
    if [ "$APPLICATION" == "" ]; then
        APPLICATION=$1
        shift
        continue
    fi

    break
done

if [ "$APPLICATION" == "" ]; then
    echo "Usage: $0 [<application>] <args>..."
    exit 2
fi

if [ "$SGX" == "1" ] && [ ! -e "$APPLICATION.manifest.sgx" ]; then
    echo "Invalid application path specified ($APPLICATION.manifest.sgx does not exist)." >&2
    echo "The path should point to application configuration files, so that they can be" >&2
    echo "found after appending corresponding extensions." >&2
    exit 2
fi

if [ ! "$SGX" == "1" ] && [ ! -e "$APPLICATION.manifest" ]; then
    echo "Invalid application path specified ($APPLICATION.manifest does not exist)." >&2
    echo "The path should point to application configuration files, so that they can be" >&2
    echo "found after appending corresponding extensions." >&2
    exit 2
fi

if [ ! -f "$PAL_CMD" ]; then
    echo "$PAL_CMD not found"
    exit 1
fi

# shellcheck disable=SC2050
if [ "$SGX" == "1" ] \
&& [ @CONFIG_SGX_DRIVER@ = oot ] \
&& [ ! -e "$APPLICATION".token ] \
&& [ -f "$APPLICATION".sig ] \
&& [ -z "$GRAMINE_NO_AUTO_GET_TOKEN" ]
then
    @PREFIX@/@BINDIR@/gramine-sgx-get-token \
        --output "$APPLICATION".token \
        --sig "$APPLICATION".sig \
    >&2
fi


CMD=("${ENVS[@]}")
CMD+=("${PREFIX[@]}")
CMD+=("$PAL_CMD" "$LIBPAL_PATH" init "$APPLICATION" "$@")
exec env "${CMD[@]}"
